<template>
  <div class="apply_sale_box">
    <p class="breadcrumb mar-bt18"><router-link :to="{ name: 'orderManage' }" class="bread">订单管理</router-link>
    <i class="el-icon-arrow-right"></i><router-link :to="{ name: 'orderDetail',params:{'orderId':orderId} }" class="bread">订单详情</router-link>
    <i class="el-icon-arrow-right"></i>商品申请售后</p>
    <div class="line_title">商品信息</div>
    <div class="shopcart_box order-status-box">
      <el-row class="shopcart_tabhead">
        <el-col :span="8">商品信息</el-col>
        <el-col :span="5" class="txt-lf">商品单价</el-col>
        <el-col :span="5" >商品数量</el-col>
        <el-col :span="6" class="head-product-total">小计</el-col>
      </el-row>
      <div class="line-gray"></div>
      <div v-if="saleType === 1">
        <ul class="goods-box" v-if="JSON.stringify(cartList) !== '{}'">
          <li class="good_info_li shopcart_body">
            <div class="good_spe spu_width_8">
              <div class="shopcart_body_img">
                <img v-lazy="prefixImg + cartList.goodsImg">
                <span class="discount-tag" v-if="cartList.activity">活动</span>
              </div>
              <div class="shopcart_img_text ellipsis">
                <span>{{cartList.goodsName}}<span v-show="cartList.other"> - {{cartList.other}} </span> </span>
                <p>{{cartList.productName}}</p>
              </div>
            </div>
            <div class="good_price spu_width_5">¥{{cartList.price}}</div>
            <div class="good_number spu_width_5">
              <el-input-number class="input-num-self" 
                @keydown.110.native.prevent=""
                v-model="cartList.number" 
                :min="1" :max="maxNumber"
                :step="cartList.packingNum"
                ref="applyInput"
                @change="handleChange($event, cartList.packingNum)"
                ></el-input-number>
            </div>
            <div class="good_total spu_width_6" :class="{'disabled-text': cartList.inventoryStatus===3, 'active-price': parseFloat(cartList.pmtAmount) > 0}">
              ¥{{cartList.pmtAmount > 0 ? (cartList.number * cartList.price - cartList.pmtAmount).toFixed(2) : (cartList.number * cartList.price).toFixed(2)}}
                <p class="prefer-price" v-if="parseFloat(cartList.pmtAmount) > 0"> 已优惠¥{{cartList.pmtAmount | floatPrices}}元 
                </p>
            </div>
          </li>
        </ul>
      </div>
      <!-- saleType === 'refund' -->
      <div v-if="saleType === 0">
        <ul class="goods-box" v-if="JSON.stringify(cartList) !== '{}'">
          <li class="good_info_li shopcart_body">
            <div class="good_spe spu_width_8">
              <div class="shopcart_body_img">
                <img v-lazy="prefixImg + cartList.goodsImg">
                <span class="discount-tag" v-if="cartList.activity">活动</span>
              </div>
              <div class="shopcart_img_text ellipsis">
                <span><em v-show="cartList.brandName">【{{cartList.brandName}}】</em>{{cartList.goodsName}}<span v-show="cartList.other"> - {{cartList.other}} </span> </span>
                <p>{{cartList.productName}}</p>
              </div>
            </div>
            <div class="good_price spu_width_5">¥{{cartList.price}}</div>
            <div class="good_number spu_width_5" style="margin: 0 auto;">
              {{maxNumber}}
            </div>
            <div class="good_total spu_width_6" :class="{'disabled-text': cartList.inventoryStatus===3, 'active-price': parseFloat(cartList.pmtAmount) > 0}">
              ¥{{cartList.pmtAmount > 0 ? (cartList.number * cartList.price - cartList.pmtAmount).toFixed(2) : (cartList.number * cartList.price).toFixed(2)}}
                <p class="prefer-price" v-if="parseFloat(cartList.pmtAmount) > 0"> 已优惠¥{{cartList.pmtAmount | floatPrices}}元 
                </p>
            </div>
          </li>
        </ul>
      </div>
    </div>
    <div class="line_title">
      <em class="color-red">*</em>收款信息
      <a class="color-blue vert_bottom right ft-14" @click="gatheringVisi = true" v-if="form.payee">修改</a>
      <a class="color-blue right ft-14" @click="gatheringVisi = true" v-else>添加信息</a>
    </div>
    <div class="order-status-box border-bt">
      <template v-if="form.payee">
         <div class="gathering-box">
          <p>收款对象:{{form.payee}}</p>
          <p>收款方式:{{form.paymentMethod}}</p>
          <p>收款账户:{{form.paymentAccount}}</p>
        </div>
        <!-- <a class="color-blue vert_bottom" @click="gatheringVisi = true">修改</a> -->
      </template>
      <!-- <a class="color-blue" @click="gatheringVisi = true" v-else>添加信息</a> -->
    </div>
    <div class="line_title"><em class="color-red">*</em>售后原因</div>
    <div class="order-status-box border-bt" v-if="saleType === 0">
      <el-select v-model="reasonType" placeholder="请选择" style="width: 353px;">
        <el-option label="商品拍错" value="0"></el-option>
        <el-option label="取消商品购买" value="1"></el-option>
        <el-option label="商品无货" value="2"></el-option>
        <el-option label="其他" value="100"></el-option>
      </el-select>
    </div>
    <div class="order-status-box border-bt" v-else>
      <el-select v-model="reasonType" placeholder="请选择" style="width: 353px;">
        <el-option label="商品包装及产品原因" value="3"></el-option>
        <el-option label="产品损坏" value="4"></el-option>
        <el-option label="商品不合格" value="5"></el-option>
        <el-option label="订单发货错误" value="6"></el-option>
        <el-option label="其他" value="100"></el-option>
      </el-select>
    </div>
    <div class="line_title">其他原因</div>
    <div class="order-status-box border-bt">
      <textarea v-model="otherReason" class="el-textarea__inner" style="min-height: 155px;width:353px" placeholder="请输入其他售后原因（不得多余250字）"maxlength="250" @change="textCounter"@keyup="textCounter"></textarea>
      <span class="word_num">{{textLen}}/<em>250</em></span>
    </div>
    <template v-if="saleType === 1">
      <div class="line_title">上传图片</div>
      <div class="order-status-box border-bt">
        <el-upload
        action="http://192.168.1.120:8080/common/image"
        list-type="picture-card"
        :http-request="handleHttp"
        :limit="limit"
        :on-exceed="exceed"
        :multiple="multiple"
        :on-remove="handleRemove"
        :before-upload="beforeUpload"
        ref="uploadRef"
        accept="image/*">
        <i class="el-icon-plus"></i>
      </el-upload>
      <el-dialog :visible.sync="dialogVisible" size="tiny">
        <img width="100%" :src="dialogImageUrl" alt="">
      </el-dialog>
      </div>
    </template>
    <div class="txt-center">
      <span class="btn-large" @click="submitApply">提交申请</span>
    </div>
    <section class="order-rules" v-if="saleType === 1">
      <h1 class="title">售后规则说明：</h1>
      <p class="content">(1)已发货的订单可申请售后退货，待商品寄回后，商家进行商品验收合格将直接退款</p>
      <p class="content">(2)待发货的订单可申请售后退款，商家将直接退款</p>
      <p class="content">(3)最终解释权归刀具联盟平台所有</p>
    </section>
    <section class="order-rules" v-if="saleType === 0">
      <h1 class="title">售后规则说明：</h1>
      <p class="content">(1)申请退款后，将由专属客服进行退款审核</p>
      <p class="content">(2)审核通过后，将在2～3个工作日内进行退款</p>
      <p class="content">(3)若退款申请失败，货品仍将继续派送</p>
      <p class="content">(4)货品退款最终解释权归刀具联盟平台所有</p>
    </section>
    <!-- 弹窗 -->
    <section class="pop txt-center" v-if="applySalesVisi">
      <p class="pop-header">退货申请</p>
      <div class="sale-content txt-center">
        <h1 class="title">请再次确认您要退款的商品</h1>
        <div class="sale-order">
          <p class="sale-line"><span>售后商品:</span>{{cartList.goodsName}} {{cartList.productName}}</p>
          <p class="sale-line"><span>售后数量:</span>x{{cartList.number}}</p>
        </div>
        <div class="txt-center mar-top20">
          <a class="btn-pop-yellow" @click="fetchSaleApply">确定</a>
        </div>
      </div>
    </section>
    <section class="pop txt-center" v-if="gatheringVisi">
      <i class="icon el-icon-circle-close-outline pop-close pointer" @click="gatheringVisi = false, trackingNumber = ''"></i>
      <p class="pop-header">收款信息</p>
      <div class="sale-content txt-center">
        <div class="sale-order" style="width: 100%;">
          <li class="sale-line">
            <span class="input-tit"><em class="color-red">*</em>公司抬头/收款人:</span>
            <el-input type="text" class="sale-input"placeholder="请输入公司抬头或收款人" v-model="input.payee" ></el-input>
          </li>
          <li class="sale-line">
            <span class="input-tit"><em class="color-red">*</em>收款方式:</span>
            <el-input type="text" class="sale-input" placeholder="请选择收款方式" v-model="input.paymentMethod"></el-input>
            <!-- <el-select v-model="input.paymentMethod" placeholder="请选择收款方式" >
              <el-option label="银行账户" value="0"></el-option>
              <el-option label="支付宝账户" value="1"></el-option>
            </el-select> -->
          </li>
          <li class="sale-line">
            <span class="input-tit"><em class="color-red">*</em>收款账号:</span>
            <el-input type="text" class="sale-input" placeholder="请输入收款账号" v-model="input.paymentAccount"></el-input>
          </li>
          <p v-show="errorinput" class="color-red ft-12 error">请填写完整!</p>
        </div>
        <div class="txt-center mar-top20">
          <a class="btn-pop-yellow" @click="setGatherInfo">添加</a>
        </div>
      </div>
    </section>
    <div class="v-modal" tabindex="0" style="z-index: 2006;" v-if="applySalesVisi || gatheringVisi"></div>
  </div>
</template>

<script>
import {Form, FormItem, Select, Option, Input, Row, Col, InputNumber, Upload, Dialog} from 'element-ui'
import {prefixImg} from '@/tool/index'
import {uploadImg, getSaleApply} from '@/service/get-data'
import {getSession} from '@/config/mUntils'
export default {
  components: {
    elForm: Form,
    elFormItem: FormItem,
    elSelect: Select,
    elOption: Option,
    elInput: Input,
    elRow: Row,
    elCol: Col,
    elInputNumber: InputNumber,
    elUpload: Upload,
    elDialog: Dialog
  },
  data () {
    return {
      cartList: {},
      applySalesVisi: false,
      gatheringVisi: false, // 收款信息弹窗
      otherReason: '',
      reasonType: '',
      // num: 0, // 申请的数量
      businessLicense: '',
      imageUrl: '',
      isEnlargeimg: '',
      saleFilePath: '',
      imgs: '', // 上传图片地址
      limit: 3,
      multiple: true,
      voucherArr: [],
      dialogVisible: false,
      dialogImageUrl: '',
      maxNumber: 0, // 最大输入值
      form: {
        payee: '',
        paymentMethod: '',
        paymentAccount: ''
      },
      input: {
        payee: '',
        paymentMethod: '',
        paymentAccount: ''
      },
      errorinput: false
    }
  },
  computed: {
    orderId () {
      return this.$route.query.orderId
    },
    saleType () {
      return this.$route.query.saleType === 'refund' ? 0 : 1
    },
    orderItemId () {
      return this.$route.query.orderItemId
    },
    prefixImg () {
      return prefixImg
    },
    textLen () {
      return this.otherReason.length
    },
    vouchers () {
      if (!this.voucherArr) return ''
      let arr = this.voucherArr
      let str = ''
      let len
      if (arr.length < 1) return
      arr.map((item, index) => {
        str += item.filePath + ','
      })
      len = str.length
      return str.substr(0, len - 1)
    }
  },
  methods: {
    // 购物车填写数字
    handleChange (value, step = 1) {
      let lastNum = value % step
      let leftNum = lastNum === 0 ? value : value - lastNum + step
      this.cartList.number = leftNum
      this.$nextTick(() => {
        this.$refs.applyInput.$refs.input.setCurrentValue(leftNum)
      })
    },
    // 收款信息
    setGatherInfo () {
      for (let key in this.input) {
        if (!this.input[key]) {
          this.errorinput = true
          return
        }
      }
      this.form = JSON.parse(JSON.stringify(this.input))
      this.gatheringVisi = false
    },
    handleRemove (file, fileList) {
      let uid = file.uid
      let index
      this.voucherArr.map((item, i) => {
        if (item === uid) {
          index = i
        }
      })
      this.voucherArr.splice(index, 1)
    },
    exceed (files, fileList) {
      this.$message({
        message: '最多上传3张图片',
        type: 'error'
      })
    },
    // 获取单品
    getGoods () {
      let obj = getSession('saleObj')
      if (!obj) {
        this.$router.push({name: 'orderDetail', params: {'orderId': this.orderId}})
        return
      }
      this.cartList = JSON.parse(obj)
      this.maxNumber = this.cartList.number - this.cartList.afterSaleNum
    },
    // 原因的字数
    textCounter () {
      if (this.textLen + 1 > 250) {
        this.$message({
          message: '字数最多250个',
          type: 'danger'
        })
        this.otherReason = this.otherReason.substring(0, 250)
      }
    },
    beforeUpload (file) {
      const reg = /^image\/+(JPEG|jpeg|JPG|jpg|png|PNG|gif)$/
      const isImg = reg.test(file.type)
      if (!isImg) {
        this.$message.error('上传图片只能是图片格式!')
      }
      return isImg
    },
    handleAvatarPreview (res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    // 上传图片
    async handleHttp (file) {
      let uid = file.file.uid
      let obj = {}
      let param = new FormData() // 创建form对象
      param.append('files', file.file, file.name)  // 通过append向form对象添加数据
      let res = await uploadImg(param)
      if (res.data.resultCode && res.data.resultCode === 2000) {
        res = res.data
        res.data.map((item, index) => {
          obj.uid = uid
          obj.filePath = item.filePath
        })
      }
      this.voucherArr.push(obj)
    },
    // 提交申请
    submitApply () {
      if (!this.reasonType) {
        this.$message({
          message: '请选择退货原因',
          type: 'error'
        })
        return false
      }
      if (!this.form.payee) {
        this.$message({
          message: '请填写退款信息',
          type: 'error'
        })
        return false
      }
      if (this.saleType === 1) {
        this.applySalesVisi = true
        return false
      }
      this.fetchSaleApply()
    },
    // 申请售后
    async fetchSaleApply () {
      this.saleType === 1 ? this.resultnumber = this.cartList.number : this.resultnumber = this.maxNumber
      let _this = this
      let res = await getSaleApply(this.orderItemId, this.reasonType, this.otherReason, this.resultnumber, this.saleType, this.vouchers, this.form.payee, this.form.paymentMethod, this.form.paymentAccount)
      if (res.data.resultCode && res.data.resultCode === 2000) {
        // console.log(res.data.data)
        let afterid = res.data.data
        _this.$router.push({name: 'serviceSuccess', query: {orderId: _this.orderId, type: _this.saleType, afterid: afterid}})
      } else {
        this.$message({
          type: 'error',
          message: res.data.resultMsg
        })
        _this.$router.push({name: 'orderDetail', params: {orderId: _this.orderId}})
      }
    }
  },
  mounted () {
    this.getGoods() // session 获取退货单
  }
}
</script>

<style lang="scss" scoped>
  @mixin wh($width, $height){
    width: $width;
    height: $height;
  }
  $org_color: #F55923;
  .line_title{
    color: #333;
    font-size:18px;
    margin-bottom:18px;
  }
  .order_box{
    margin-bottom:30px;
  }
  .good_info_li{
    position: relative;
    display: inline-block;
    color: #474747;
    width: 100%;
    padding: 22px 0;
    background-color: #ffffff;
    border-bottom:1px solid #DCDCDC;
  }
  .good_spe{text-align: left;vertical-align: middle;}
  .shopcart_body_img{
      position: relative;
      display:inline-block;
      @include wh(70px, 70px);
      vertical-align: top;
      margin-left: 15px;
      & > img{
        width: 100%;
        height:100%;
      }
    }
    .shopcart_img_text{
      width:190px;
      display:inline-block;
      line-height:2.0;
      padding-left: 12px;
      font-size: 14px;
    }
    .good_price{
      text-align: left;
      vertical-align: middle;
    }
    .good_number{
      margin: 0px auto;
      text-align: center;
      margin-left: -10px;
    }
    .good_stock {
      font-size: 14px;
      text-align: center;
    }
    .good_total{
      width:23%;
      font-size: 18px;
      font-weight: 600;
      color: $org_color;
      text-align: center;
      box-sizing: border-box;
      vertical-align: middle;
    }
    .shopcart_tabhead{
      height: 45px;
      line-height: 45px;
      text-align: center;
      font-size: 16px;
      color: #474747;
      background: #ffffff;
      border-bottom: 1px solid #dcdcdc;
      border-top: 1px solid #dcdcdc;
    }
  .prefer-price{
      color: #474747;
      font-size: 12px;
    }
    .border-bt{
      border-bottom:1px solid #dcdcdc;
    }
    .order-status-box{
      padding-bottom: 30px;
      margin-bottom:30px;
    }
    .word_num{
      margin-top:5px;
      width: 353px;
      text-align: right;
      display: inline-block;
    }
    .avatar-uploader{
      width: 178px;
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }
  .avatar-uploader-icon{
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      line-height: 178px;
      text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .order-rules{
    margin-top:80px;
    .title{
      color:#6B6B6B;
      font-size: 14px;
      line-height:20px;
      margin-bottom:10px;
    }
    .content{
      color: #999999;
      line-height:18px;
      margin-bottom:6px;
      font-size: 13px;
    }
  }
  .error{
    padding-left: 33%;
  }
  .gathering-box{
    border: 1px solid #CBCBCB;
    padding: 22px 20px;
    color: #333333;
    line-height: 28px;
  }

</style>
